package com.scproject.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scproject.annotations.LoginVerifyToken;
import com.scproject.annotations.PassToken;
import com.scproject.dto.ResponseDto;
import com.scproject.utils.JWTUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截请求并进行JWT验证
 * @author LNL
 * @date 2021/4/25 14:23
 */
public class JWTInterceptors implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从header中获取token
        String token = request.getHeader("token");

        //如果不是映射到方法，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //获取当前方法
        Method method = handlerMethod.getMethod();
        //判断如果方法上有PassToken注解，直接放行
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            //判断是否必须，默认为true
            if (passToken.require()) {
                return true;
            }
        }

        if (method.isAnnotationPresent(LoginVerifyToken.class)) {
            LoginVerifyToken loginVerifyToken = method.getAnnotation(LoginVerifyToken.class);
            //如果为true，进行验证
            if (loginVerifyToken.require()) {
                ResponseDto responseDto = new ResponseDto();
                try{
                    //先进行验证token
                    JWTUtils.verifyJWT(token);
                    return true;//如果没有异常就放行请求
                } catch (AlgorithmMismatchException e) {
                    responseDto.setMsg("算法不匹配");
                    e.printStackTrace();
                } catch (SignatureVerificationException e){
                    responseDto.setMsg("无效签名");
                    e.printStackTrace();
                } catch (TokenExpiredException e) {
                    responseDto.setMsg("token过期");
                    e.printStackTrace();
                } catch (Exception e) {
                    responseDto.setMsg("token无效");
                    e.printStackTrace();
                }
                responseDto.setCode("0");
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(responseDto);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().append(json);
                return false;
            }
        }
       return true;
    }
}
